/**
 * 会话消息搜索功能
 */
var sessionSearch = (function() {
    
    var userProfileTmp = [
        '<figure class="suserProfile">',
            '<div class="suserProfileImg hvBox" style="height:100px">',
                '<img src="<%=o.icon ? ujs.browser.loc.addQuery(o.icon, {w:200}) : ujs.getConfigRes("defUserIcon")%>" style="height:100px"/>',
            '</div>',
            '<div class="suserProfileSummary">',
                '<div class="suserPItem">',
                    '<label lan="lbl.account"></label>',
                    '<span><%=o.account%></span>',
                '</div>',
                '<div class="suserPItem">',
                    '<label lan="lbl.nick"></label>',
                    '<span><%=o.name%></span>',
                '</div>',
                '<div class="suserPItem" style="margin-bottom: 30px;">',
                    '<label lan="lbl.from"></label>',
                    '<span><%= $.map(o.groups, function(group){return group["name"]}).join(", ") %></span>',
                '</div>',
                '<% if(o.id != ujs.util.session.getCurrentUserID()) { %>',
                    '<button lan="buttons.chat" style="bottom: 15px;position: absolute;right: 10px;letter-spacing: 1px;" class="suserChat" id="<%=o.id%>" onclick=page.sc(this.id)></button>',
                '<% } %>',
            '</div>',
        '</figure>'
    ];
    
    var userGroupProfileTmp = [
        '<figure class="suserProfile">',
            '<div class="suserProfileImg">',
                '<img src="<%=o.icon ? ujs.browser.loc.addQuery(o.icon, {w:200}) : ujs.getConfigRes("defGroupIcon")%>" />',
            '</div>',
            '<div class="suserProfileSummary">',                                                    
                '<div class="suserPItem">',
                    '<label lan="lbl.name"></label>',
                    '<span><%=o.name%></span>',
                '</div>',
                '<div class="suserPItem">',
                    '<label lan="lbl.desp"></label>',
                    '<span><%=o.description%></span>',
                '</div>',
                '<button lan="buttons.chat" style="bottom: 10px;position: absolute;right: 10px;letter-spacing: 1px;" class="suserChat" id="<%=o.id%>" name="<%=o.name%>" icon="<%=o.icon%>" onclick=page.sc2(this)></button>',
            '</div>',
        '</figure>'
    ];
    
    return Observable.create({
        init : function($holder){
            var _this = this;
            this.$holder = $holder;
            //顶部搜索条.
            $holder.searchable({
                theme : 'topSearch',
                placeholder : 'Search ...',
                isShowSearchBtn : false,
                onKeyup : function(val){                    
                    sessionList.$wrapper.find('.sessionListItem').filterByText(val, '.sessionTitle');
                },
                //搜索提交时.
                onSearch : function(val, searchType, $searchBox) {
                    page.isSearching = true;
                    _this.val = val.replace(/\*/gi,''); 
                    if(!_this.val){
                        return;
                    }      
                    $('#searchResult').css('width', page.defLeftWidth);              
                    
                    //先获取消息数目.
                    $.get(
                        '/apis/search/count?q={0}&qm={1}'.format(
                            encodeURIComponent(_this.val),
                            encodeURIComponent('content:({key})'.format({
                                key : _this.val
                            }))
                        )
                    ).done(ujs.hr(function(msg) {
                        if(!$('#searchResult').is(':visible')){                        
                            _this.showResultTab();                 
                        }
                        page.searchTab.addTabHeaderThumb('msgList', msg['topicTotal'] || 0);
                        page.searchTab.addTabHeaderThumb('userList', msg['userTotal'] || 0);
                        page.searchTab.addTabHeaderThumb('groupList', msg['userGroupTotal'] || 0); 
                        $('#searchResult').data('tabControl').selectMaxThumbTabItem();                        
                    }));                    
                                                         
                    //消息搜索
                    var msgResult = $('.msgResult').data('listView');
                    msgResult.showMask();
                    var msgSearchPromise = $.ajax({
                        url : '/apis/chat/search/topic?q={query}&l={limit}&o={offset}'.format({
                            query : encodeURIComponent('content:({key})'.format({
                                key : _this.val
                            })),
                            limit : 300,
                            offset : 0
                        }) 
                    }).then(ujs.hr(function(msg) {       
                        window.extraTe = msg['tes'];                   
                        msgResult.load(msg['topics']);
                    }));  
                                  
                    //用户搜索.
                    var userResult = $('.userResult').data('listView'); 
                    userResult.showMask('loading');
                    var userSearchPromise = $.ajax({
                        url : '/apis/usergroup/users/search?q={0}&o=&l='.format(encodeURIComponent(_this.val))
                    }).then(ujs.hr(function(msg){
                        userResult.load(msg['users']);                        
                        userResult.$wrapper.find('.listViewItem').tooltipster({
                            interactive : true,                          
                            position : 'right',
                            theme : 'tooltipster-light',
                            trigger : 'click',
                            content: 'Loading...',
                            contentAsHTML : true,
                            functionBefore: function(origin, continueTooltip) {                                
                                var uid = this.find('.searchUserName').attr('id');
                                continueTooltip();                                
                                if (origin.data('ajax') !== 'cached') {
                                    var $tip = $(tmpl(userProfileTmp, userResult.store.getItem(uid)));
                                    lan.parse($tip);
                                    origin.tooltipster('content', $tip).data('ajax', 'cached');                                                                            
                                }
                            }
                        });
                    }));
                                                        
                    //用户组搜索.
                    var groupResult = $('.groupResult').data('listView');
                    groupResult.showMask('loading');
                    var userGroupSearchPromise = $.ajax({
                        url : '/apis/usergroup/search?q={0}&o=&l='.format(encodeURIComponent(_this.val))
                    }).then(ujs.hr(function(msg){                        
                        groupResult.load(msg['usergroups']);                                               
                        groupResult.$wrapper.find('.listViewItem').tooltipster({   
                            interactive : true,                          
                            position : 'right',
                            trigger : 'click',
                            theme : 'tooltipster-light',
                            content: 'Loading...',
                            contentAsHTML : true,
                            functionBefore: function(origin, continueTooltip) {
                                var gid = this.find('.searchUserName').attr('id');
                                continueTooltip();                                
                                if (origin.data('ajax') !== 'cached') {  
                                    var $tip = $(tmpl(userGroupProfileTmp, groupResult.store.getItem(gid)));
                                    lan.parse($tip);                                  
                                    origin.tooltipster('content', $tip).data('ajax', 'cached');                                                                            
                                }
                            }
                        });
                    }));
                },
                //取销搜索时.
                onCancelSearch : function($searchBox) {
                    page.isSearching = false;
                    _this.hideResultTab();
                    sessionList.$wrapper.find('.sessionListItem').filterByText('', '.sessionTitle');
                    if(page.contentCardLayout.getActiveItem().mode == 'view'){
                        page.contentCardLayout.showItem('dashboard');
                    }            
                }
            });    
        },
        showResultTab : function(){
            $('#searchResult').show();
        },
        hideResultTab : function(){
            $('#searchResult').hide();
        },
        getCurrentTabID : function(){
            return $('#searchResult li.tabNavItem.current').attr('relid');
        }
    });
})(); 